package middleware

import (
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
	"product/api/internal/types"
	"product/pkg"
)

type UserAgentMiddleware struct {
}

func NewUserAgentMiddleware() *UserAgentMiddleware {
	return &UserAgentMiddleware{}
}

func (m *UserAgentMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// TODO generate middleware implement function, delete after code implementation

		token := r.Header.Get("token")
		if token == "" {
			response := types.Response{
				Message: "用户未登录",
				Data:    nil,
				Code:    "500",
			}
			httpx.OkJsonCtx(r.Context(), w, response)
			return
		}
		getToken, errString := pkg.GetToken(token)
		if errString != "" {
			response := types.Response{
				Message: errString,
				Data:    nil,
				Code:    "500",
			}
			httpx.OkJsonCtx(r.Context(), w, response)
			return
		}
		id := getToken["id"].(string)
		r.ParseForm()
		r.Form.Set("userid", id)

		// Passthrough to next handler if need
		next(w, r)
	}
}
